package com.huaweicloud.controller;

import com.alibaba.fastjson.JSON;
import com.huaweicloud.OBSStorageFeign;
import com.huaweicloud.commons.config.OBSParams;
import com.huaweicloud.commons.outhUtils.JwtUtil;
import com.huaweicloud.commons.outhUtils.RequestUtil;
import com.huaweicloud.commons.pojo.OBSStorageParams;
import com.huaweicloud.commons.pojo.User;
import com.huaweicloud.commons.response.ProfileResult;
import com.huaweicloud.commons.response.Result;
import com.huaweicloud.commons.response.ResultCode;
import com.huaweicloud.service.impl.UserServiceImpl;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户管理接口，如用户登录、用户信息获取
 */

@CrossOrigin
@RestController
@RequestMapping("/user")
@Log4j2
public class UserController {

    @Autowired
    JwtUtil jwtUtil;
    @Autowired
    RequestUtil requestUtil;
    @Autowired
    UserServiceImpl userService;
    @Autowired
    OBSParams obsParams;
    @Autowired
    OBSStorageFeign obsStorageFeign;

    @PostMapping("/login")
    public Result login(@RequestBody Map<String, String> loginMap) {

        //1、校验用户联系方式 和 用户名密码
        Map<String, String> map = new HashMap<>();
        String mobile = loginMap.get("mobile");
        String password = loginMap.get("password");
        User user = userService.findByMobile(mobile);

        //2、判断是否存在
        if (user == null || !user.getPassword().equals(password)) {
            //(1)若用户不存在，返回失败
            return new Result(ResultCode.FAIL);
        } else {
            //(2)若用户存在，生产Token,并返回Token
            map.put("mobile", user.getMobile());
            map.put("username", user.getUsername());
            map.put("iconURL", user.getIconURL());
            String token = jwtUtil.getToken(user.getId(), map);

            return new Result(ResultCode.SUCCESS, token);
        }
    }

    /**
     * 获取用户个人信息
     *
     * @param request HttpServletRequest 请求参数；
     * @return 个人信息获取参数；
     */
    @PostMapping("/profile")
    public Result profile(HttpServletRequest request) {
        String userId = null;
        try {
         //1、获取用户请求ID
            userId = (String) request.getHeader("userId");
        } catch (Exception e) {
            e.printStackTrace();
        }
        //2、通过id，获取用户名
        User user = userService.findUserById(userId);

        //3、返回用户获取结果
        return new Result(ResultCode.SUCCESS, new ProfileResult(user));
    }

    @PostMapping("/UpdateIconImage")
    public Result upLoadOne(@RequestParam("file") MultipartFile multipartFile, HttpServletRequest request) {

        String filename ;
        String dt ;
        String originalFilename;

        //1、获取用户请求ID
        String userId = (String) request.getHeader("userId");

        //2、获取请求用户对象
        User user = userService.findUserById(userId);

        if (multipartFile.isEmpty()) {
            log.info("error", "空文件");
            return new Result(ResultCode.FAIL);
        }

        //4、获取上传文件名，拼接成带有时间戳的文件名
        originalFilename = multipartFile.getOriginalFilename();
        dt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());

        if (originalFilename.contains(".")) {
            String[] tempFileName = originalFilename.split("[.]");
            filename = tempFileName[0].concat(dt).concat(".").concat(tempFileName[1]);

        } else {
            filename = originalFilename.concat(dt);
        }

        //5、从数据库中查询user icon地址
        String iconURL = user.getIconURL();
        String deleobjectname = null;
        if (iconURL != null) {
            deleobjectname = iconURL.substring(iconURL.indexOf("443/") + 4);
        }

        //6、设置obsParams 存储对象名参数
        OBSStorageParams obsStorageParams = new OBSStorageParams();
        BeanUtils.copyProperties(obsParams, obsStorageParams);
        obsStorageParams.setObjectname("dtsetraining" + "/" + filename);
        String obsParamsJson = JSON.toJSONString(obsStorageParams);
        String objURL = obsStorageFeign.upLoadOneFile(multipartFile, obsParamsJson);

        user.setIconURL(objURL);
        boolean isSuccess = userService.update(user);

        //7、删除历史版本个人icon
        if (isSuccess && iconURL != null) {
            Result result = obsStorageFeign.deleteOneFile(obsStorageParams, deleobjectname);
            if (result.isSuccess()) {
                log.info("文件" + deleobjectname + "删除成功");
            } else {
                log.info("文件" + deleobjectname + "删除失败");
            }
        }

        //8、返回icon更新结果
        return new Result(ResultCode.SUCCESS, new ProfileResult(user));
    }

}
